//
//  IGHomeDailyVC.m
//  jingdongfang
//
//  Created by LJL on 2018/5/21.
//  Copyright © 2018年 BOE. All rights reserved.
//

#import "IGHomeDailyVC.h"
#import "CollectionReusableViewTitle1.h"
#import "HomeDailyView.h"
#import "IGHomeDailyBannerApi.h"
#import "IGHomeDailySingleApi.h"
#import "WSLWaterFlowLayout.h"
#import "IGPicListMainCollectionViewCell.h"
#import "XiangQingViewController.h"
#import "ArtOperationView.h"
#import "UIImage+ImageEffects.h"
#import "IGMoreWorksSelectVC.h"
#import "IGPushiGalleryListVC.h"
#import "IGiGalleryListApi.h"
#import "NotFindDeviceView.h"
#import "IGMyiGalleryVC.h"

@interface IGHomeDailyVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, CollectionReusableViewTitle1Delegate,WSLWaterFlowLayoutDelegate,IGPicListMainCollectionViewCellDelegate>{
    UILabel* titlelable;
    UIBarButtonItem *backButton;
    NotFindDeviceView *findView;
}
@property (nonatomic, strong) UICollectionView *collectionV;
@property (nonatomic, strong) HomeDailyView *headerView;
@property (nonatomic, strong) IGHomeDailyBannerApi *bannerApi;
@property (nonatomic, strong) IGArtWorkModel *bannerModel;
@property (nonatomic, strong) NSMutableArray * dataArr;
@property (nonatomic, strong) IGHomeDailySingleApi *api;
@property (nonatomic, strong) IGiGalleryListApi *igalleryListApi;
@property (nonatomic, strong) NSArray *iGalleryListArr;

@end

@implementation IGHomeDailyVC

-(UICollectionView *)collectionV
{
    if (!_collectionV)
    {
        WSLWaterFlowLayout * layout = [[WSLWaterFlowLayout alloc] init];
        layout.delegate = self;
        layout.flowLayoutStyle = WSLVerticalWaterFlow;
        _collectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - NavigationMagin) collectionViewLayout:layout];
        if (@available(iOS 11.0, *))
        {
            _collectionV.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _collectionV.scrollIndicatorInsets = _collectionV.contentInset;
        }
        _collectionV.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _collectionV.clipsToBounds = NO;
        _collectionV.dataSource = self;
        _collectionV.delegate = self;
        _collectionV.backgroundColor = [UIColor c3Color];
        [_collectionV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader"];
        [_collectionV registerClass:[CollectionReusableViewTitle1 class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CollectionReusableViewTitle1"];
//        [_collectionV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
[_collectionV registerClass:[IGPicListMainCollectionViewCell class] forCellWithReuseIdentifier:@"IGPicListMainCollectionViewCell"];
    }
    return _collectionV;
}

- (void)didTapBackButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UINavigationBar * bar = self.navigationController.navigationBar;
    //首次透明
    [bar setTranslucent: true];;
    [bar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [bar setShadowImage:[[UIImage alloc] init]];
    
    //设置起始坐标为0
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [self scrollViewDidScroll:self.collectionV];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
    self.navigationController.navigationBar.subviews[0].alpha = 1.0;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:254.0/255.0 green:254.0/255.0 blue:254.0/255.0 alpha:1.0];
    [self.navigationController.navigationBar setBackgroundImage:[self createImageWithColor:[UIColor colorWithRed:254.0/255.0 green:254.0/255.0 blue:254.0/255.0 alpha:1.0]] forBarMetrics:UIBarMetricsDefault];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.collectionV];
    self.view.backgroundColor = [UIColor c2Color];
    UIImage *backButtonImage  = [UIImage imageNamed:@"wallet-back"];
    backButtonImage = [backButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    backButton = [[UIBarButtonItem alloc] initWithImage:backButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(didTapBackButton)];
    self.navigationItem.leftBarButtonItem = backButton;
    
    titlelable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, GSCALE(100) , GSCALE(44))];
    titlelable.font = [UIFont boldSystemFontOfSize:20];
    titlelable.textColor = [UIColor whiteColor];
    titlelable.textAlignment = NSTextAlignmentCenter;
    titlelable.text = NSLocalizedString(@"home6", nil);
    self.navigationItem.titleView = titlelable;

    [self setCollectionHeaderView];
    
    [self initBaseData];
    
    [self dataRequest];
}

- (void)setCollectionHeaderView
{
    self.headerView = [[HomeDailyView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, kColViewHeight)];
}


- (void)initBaseData
{
    self.bannerApi = [IGHomeDailyBannerApi new];
    self.api = [IGHomeDailySingleApi new];
    self.bannerModel = [IGArtWorkModel new];
    self.dataArr = [@[] mutableCopy];
}

- (void)dataRequest
{
    __weak typeof(self) weakSelf = self;
    [self.bannerApi startWithDecodeClass:[IGHomeDailyBannerResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            IGHomeDailyBannerResp *resp = responseObject;
            IGHomeDailyBannerModel *model = resp.data;
            _bannerModel = model.product;
            [weakSelf.headerView setIconPicStr:_bannerModel.image withCompleteBlock:^{
                //回调后刷新navigationBar
                [weakSelf scrollViewDidScroll:weakSelf.collectionV];
            }];
        }
    }];
    [self.api startWithDecodeClass:[IGHomeDailySingleResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            IGHomeDailySingleResp *resp = responseObject;
            IGHomeDailySingleModel *model = resp.data;
            _dataArr = [NSMutableArray arrayWithArray:model.productList];
            [_collectionV reloadData];
        }
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
  if (section == 1)
  {
        return self.dataArr.count ? : 0;
    }
    return 0;
}

- (CGFloat)waterFlowLayout:(WSLWaterFlowLayout *)waterFlowLayout heightForItemAtIndexPath:(NSIndexPath *)indexPath itemWidth:(CGFloat)itemWidth
{
    if (indexPath.section == 1)
    {
        IGArtWorkModel *base = _dataArr[indexPath.item];
        if ([base.plates integerValue]==1)
        {
            //横板
            return ((KSCREENWIDTH-16)/2*1080/1920);
        }
        else if ([base.plates integerValue]==2)
        {
            //坚板
            return ((KSCREENWIDTH-16)/2*1920/1080);
        }
    }
    return 0;
}
/** 头视图Size */
-(CGSize )waterFlowLayout:(WSLWaterFlowLayout *)waterFlowLayout sizeForHeaderViewInSection:(NSInteger)section
{
    if (section == 0)
    {
        return CGSizeMake(KSCREENWIDTH,kColViewHeight);
    }
    else
    {
        return CGSizeMake(KSCREENWIDTH, 50);
    }
}
/** 脚视图Size */
-(CGSize )waterFlowLayout:(WSLWaterFlowLayout *)waterFlowLayout sizeForFooterViewInSection:(NSInteger)section
{
    return CGSizeZero;
}
- (UIEdgeInsets)edgeInsetInWaterFlowLayout:(WSLWaterFlowLayout *)waterFlowLayout
{
    return  UIEdgeInsetsZero;
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 0)
    {
        return CGFLOAT_MIN;
    }
    else
    {
        return 0;
    }
    
}
//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 0)
    {
        return CGFLOAT_MIN;
    }
    else
    {
        return 2;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        IGPicListMainCollectionViewCell*cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"IGPicListMainCollectionViewCell" forIndexPath:indexPath];
        IGArtWorkModel *base = _dataArr[indexPath.item];
        ((IGPicListMainCollectionViewCell *)cell).dataModel = base;
        ((IGPicListMainCollectionViewCell *)cell).delegate = self;
        return cell;
    }
    return nil;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
        if (indexPath.section == 0)
        {
            UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader" forIndexPath:indexPath];
            [headerView addSubview:self.headerView];
            @KWeakObj(self)
            self.headerView.block = ^{
                [selfWeak clickRightView];
            };
            return headerView;
        } else if (indexPath.section == 1) {
            CollectionReusableViewTitle1 *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CollectionReusableViewTitle1" forIndexPath:indexPath];
            headerView.totolNum.text = [NSString stringWithFormat:@"(%lu)",_dataArr.count];
            headerView.delegate = self;
            return headerView;
        }
    return nil;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        IGArtWorkModel *base = _dataArr[indexPath.item];
        XiangQingViewController * vc = [[XiangQingViewController alloc] init];
        vc.p_id = base.aId;
        vc.isRoot = NO;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)clickRightView
{
    XiangQingViewController * vc = [[XiangQingViewController alloc] init];
    vc.p_id = _bannerModel.aId;
    vc.isRoot = NO;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - CollectionReusableViewTitle1Delegate（全部上传）
- (void)clickAllPull
{
    __weak typeof(self) weakSelf = self;
    self.igalleryListApi = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
    [self.igalleryListApi startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            IGiGalleryListResp *resp = responseObject;
            IGiGalleryListModel *model1 = resp.data;
            weakSelf.iGalleryListArr = [NSArray arrayWithArray:model1.equs];
            if (self.iGalleryListArr.count == 0)
            {
                findView = [NotFindDeviceView showNotFindDeviceView];
                findView.bangdingBlock = ^{
                    [UIViewController ig_pushViewControllerClass:[IGMyiGalleryVC class] animated:YES];
                };
            } else {
                IGPushiGalleryListVC *listVC = [[IGPushiGalleryListVC alloc] initWithType:IGPushiGalleryTypeNN];
                listVC.recommendArr = weakSelf.dataArr;
                [UIViewController ig_pushViewController:listVC animated:YES];
            }
        }
    }];
}

#pragma mark - CollectionReusableViewTitle1Delegate（多选按钮）
- (void)clickSelectMore
{
    IGMoreWorksSelectVC *vc=[[IGMoreWorksSelectVC alloc]initWithType:dayRecType];
    vc.recDataArr=_dataArr;
    [UIViewController ig_pushViewController:vc animated:YES];
}

#pragma mark - 点击右下角点点点的点击事件
- (void)clickMore:(IGArtWorkModel *)dataModel
{
    [ArtOperationView showArtOperationViewArtWork:dataModel];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.collectionV == scrollView)
    {
        CGFloat y = self.collectionV.contentOffset.y;
        if (y < - KHeadViewOff)
        {
            [self.collectionV setContentOffset:CGPointMake(0, - KHeadViewOff + 1) animated:0];
        }
        
        if ( y < kColViewHeight)
        {
            //截图背景图的部分截图 用于设置navigatonBar背景图，造成连贯视觉落差
            UIImage * view = [self getImageFromView:self.headerView.backgroundImageView withContentOffY: -(self.collectionV.contentOffset.y) - KHeadViewOff];
            [self.navigationController.navigationBar setBackgroundImage:view forBarMetrics:UIBarMetricsDefault];
        }
        else
        {
            UIImage * view = [self getImageFromView:self.headerView.backgroundImageView withContentOffY:-kColViewHeight -KHeadViewOff];
            [self.navigationController.navigationBar setBackgroundImage:view forBarMetrics:UIBarMetricsDefault];
        }
    }
}

/**
 截取图片
 
 @param orgView 哪个view
 @param y 起始点
 @return 截取好的image
 */
-(UIImage *)getImageFromView:(UIImageView *)orgView withContentOffY:(CGFloat)y{
    
    UIGraphicsBeginImageContext(orgView.bounds.size);
    [orgView.image drawInRect:CGRectMake(0,y, orgView.bounds.size.width, orgView.bounds.size.height)];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}



@end
